package com.endpoint.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.endpoint.common.bean.UserDetails;
import com.endpoint.common.constant.ResponseStatus;
import com.endpoint.common.exception.BusinessException;
import com.endpoint.common.utils.JwtTokenUtil;
import com.endpoint.member.entity.Member;
import com.endpoint.member.service.MemberRegisterService;
import com.endpoint.member.service.MemberService;
import com.endpoint.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * @Project: endpoint
 * @Name: MemberRegisterServiceImpl
 * @Author: Jack_Li
 * @Date: 2024/7/6 9:12
 */

@Service
public class MemberRegisterServiceImpl implements MemberRegisterService {

    @Autowired
    private MemberService memberService;

    @Override
    public UserDetails register(MemberRegisterVo memberRegisterVo) {
        Member member = new Member();
        //对用户名手机号进行唯一性校验
        long count = memberService.count(new QueryWrapper<Member>().eq("username", memberRegisterVo.getUsername()));
        if(count>0){
            throw new BusinessException(ResponseStatus.USERNAME_EXIST);
        }
        member.setUsername(memberRegisterVo.getUsername());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(memberRegisterVo.getPassword());
        ////设置密码 进行加密存储.
        member.setPassword(password);
        member.setNickName(memberRegisterVo.getUsername());

        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.now();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);

        Date date = Date.from(zdt.toInstant());

        member.setCreateTime(date);
        member.setUpdateTime(date);
        memberService.save(member);

        //生成token并封装 UserDetails
        String token = JwtTokenUtil.createToken(member.getId());
        UserDetails userDetails = new UserDetails();
        userDetails.setId(member.getId());
        userDetails.setNickName(member.getNickName());
        userDetails.setToken(token);
        return userDetails;
    }
}
